package cn.zeal4j.controller;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

/**
 * @author Administrator
 * @file Spring-Security + Oauth2
 * @create 2020 09 29 12:01
 */
@Controller
@RequestMapping("user")
public class UserController {

    /**
     * 获取当前用户
     * @param authentication
     * @return user/getCurrentUser
     */
    @RequestMapping("/getCurrentUser")
    @ResponseBody
    public Object getCurrentUser(Authentication authentication) {
        return authentication.getPrincipal();
    }

    /**
     * 获取当前用户
     * @param authentication
     * @return user/getJwtToken
     */
    @RequestMapping("/getJwtToken")
    @ResponseBody
    public Object getJwtToken(HttpServletRequest httpServletRequest, Authentication authentication) {
        String authorization = httpServletRequest.getHeader("Authorization");
        String token = authorization.substring(authorization.indexOf("bearer") + 7);

        JwtParser jwtParser = Jwts.parser();
        Jws<Claims> claimsJws = jwtParser.
                setSigningKey("这不是盐【滑稽】 It's not salt [funny]".getBytes(StandardCharsets.UTF_8)).
                parseClaimsJws(token);

        Claims claimsJwsBody = claimsJws.getBody();

        return claimsJwsBody;
    }

}
